package com.pxmeta.order.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pxmeta.common.constant.Status;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.common.utils.auth.YunDunClient;
import com.pxmeta.order.dto.OrderEvaluateDTO;
import com.pxmeta.order.dto.RequestRefundDTO;
import com.pxmeta.order.entity.OrderEvaluate;
import com.pxmeta.order.service.IOrderEvaluateService;
import com.pxmeta.order.vo.OrderDetailVO;
import com.pxmeta.order.vo.OrderEvaluateVO;
import com.pxmeta.party.entity.Association;
import com.pxmeta.party.entity.Party;
import com.pxmeta.party.entity.SkillPrice;
import com.pxmeta.order.entity.UserOrderRecord;
import com.pxmeta.order.mapper.UserOrderRecordMapper;
import com.pxmeta.party.mapper.PartyMapper;
import com.pxmeta.party.service.IAssociationService;
import com.pxmeta.party.service.IPartyService;
import com.pxmeta.party.service.ISkillPriceService;
import com.pxmeta.order.service.IUserOrderRecordService;
import com.pxmeta.skill.entity.UserSkill;
import com.pxmeta.skill.entity.enums.OrderStatusEnums;
import com.pxmeta.skill.entity.vo.OrderProgressVO;
import com.pxmeta.skill.entity.vo.SkillPriceVO;
import com.pxmeta.skill.service.IUserSkillService;
import com.pxmeta.user.entity.*;
import com.pxmeta.user.service.IUserBillService;
import com.pxmeta.user.service.IUserService;
import com.pxmeta.user.service.IUserTagService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserOrderRecordServiceImpl extends ServiceImpl<UserOrderRecordMapper, UserOrderRecord> implements IUserOrderRecordService {

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;

    private final ISkillPriceService servicePriceService;
    private final IUserService userService;
    @Autowired
    private  IUserSkillService userSkillService;

    @Autowired
    private IUserTagService userTagService;

    @Autowired
    private IPartyService partyService;

    @Autowired
    private IUserBillService userBillService;

    @Autowired
    private IAssociationService associationService;

    @Autowired
    private IOrderEvaluateService orderEvaluateService;


    @Override
    public Long saveRecord(Long userId, Long targetUserId, Integer type) {
        UserOrderRecord record = new UserOrderRecord();
        record.setTargetUserId(targetUserId);
        record.setUserId(userId);
        record.setScore(0);
        record.setTotalPrice(0);
        record.setTotalCount(0);
        this.save(record);

        return record.getId();
    }

    @Override
    public void scoring(Long recordId, Integer score) {
        UserOrderRecord record = this.getById(recordId);
        if (null == record){
            throw new ServiceException("记录不存在！");
        }
        record.setScore(score);
        this.updateById(record);
    }

    @Override
    public void charging(Long userId, Long recordId, Long servicePriceId) {

        SkillPrice skillPrice = servicePriceService.getById(servicePriceId);

        UserOrderRecord record = this.getById(recordId);
        if (null == record){
            throw new ServiceException("记录不存在");
        }
        Integer totalDuration = record.getTotalCount();
        totalDuration += skillPrice.getDuration();
        Integer totalPrice = record.getTotalPrice();
        Integer price = skillPrice.getPrice();
        totalPrice += price;

        //扣减余额
        userService.subBalance(userId, price);

        record.setTotalCount(totalDuration);
        record.setTotalPrice(totalPrice);

        //判断是否已经完成交易，如果未完成，则更新为完成状态。
        Boolean isSuccess = record.getIsSuccess();
        if (!isSuccess){
            record.setIsSuccess(Boolean.TRUE);
        }

        this.updateById(record);
    }

    @Override
    public Long getOrderCount(Long userId) {
        LambdaQueryWrapper<UserOrderRecord> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserOrderRecord::getTargetUserId, userId)
                .eq(UserOrderRecord::getStatus,3);
        return this.count(wrapper);
    }

    @Override
    public void evaluate(Long userId, OrderEvaluateDTO evaluateDTO) {

        //更新订单状态为已完成
        UserOrderRecord userOrder = this.getById(evaluateDTO.getOrderId());
        userOrder.setStatus(OrderStatusEnums.COMPLETE.getStatus());
        this.updateById(userOrder);

        //记录评价信息
        //查询是否已经评价过
        LambdaQueryWrapper<OrderEvaluate> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(OrderEvaluate::getUserId, userId)
                .eq(OrderEvaluate::getOrderId, evaluateDTO.getOrderId());

        OrderEvaluate exist = orderEvaluateService.getOne(wrapper);
        if (exist!=null){
            throw new ServiceException("请勿重复评价！");
        }
        OrderEvaluate evaluate = new OrderEvaluate();
        evaluate.setContent(evaluateDTO.getContent());
        evaluate.setSkillId(userOrder.getSkillId());
        evaluate.setImg(evaluateDTO.getImg());
        evaluate.setTagIds(StrUtil.join(",",evaluateDTO.getTagIds()));
        evaluate.setOrderId(evaluateDTO.getOrderId());
        evaluate.setUserId(userId);
        evaluate.setTargetUserId(userOrder.getTargetUserId());
        evaluate.setIsAnonymous(evaluateDTO.getIsAnonymous());
        evaluate.setIsSatisfied(evaluateDTO.getIsSatisfied());
        orderEvaluateService.save(evaluate);

    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    @SneakyThrows
    public Long createOrder(Long userId, Long userSkillId, Integer count, String partyId) {

        UserOrderRecord userOrder = new UserOrderRecord();
        userOrder.setUserId(userId);
        userOrder.setTotalCount(count);
        userOrder.setStatus(OrderStatusEnums.PENDING.getStatus());
        userOrder.setPartyId(partyId);

        UserSkill userSkill = userSkillService.getById(userSkillId);
        if (userSkill == null){
            throw new ServiceException("技能不存在！");
        }

        if (userSkill.getUserId().equals(userId)){
            throw new ServiceException("不允许给自己下单哦！");
        }

        SkillPriceVO priceVO = userSkillService.getPrice(userId, userSkillId, count);
        Integer totalPrice = priceVO.getTotalPrice();
        if (priceVO.getPreferentialType()==2 && count >1){
            throw new ServiceException("首单优惠不允许超过一单哦！");
        }
        Long skillUserId = userSkill.getUserId();

        User buyer = userService.getById(userId);

        Boolean meetOneCoinFeatures = userSkillService.checkMeetOneCoinFeatures(userSkillId, userId);
        if (meetOneCoinFeatures){
            //每日一币
            userOrder.setDiscountType(1);
            totalPrice = 100;
            if (count>1){
                throw new ServiceException("每日一币不允许大于一单！");
            }
        }
        User skillUser = userService.getById(skillUserId);
        String skillUsername = skillUser.getUsername();
        //判断是否有进行中的订单
        OrderProgressVO progressVO = getOrderProgress(userId, skillUsername);
        Integer status = progressVO.getStatus();
        if (status != null){
            throw new ServiceException("有未完成的订单,不可重复下单！");
        }
        userService.subBalance(userId,totalPrice);
        userOrder.setTargetUserId(skillUserId);
        userOrder.setSkillId(userSkill.getSkillId());
        userOrder.setType(1);
        userOrder.setTotalPrice(totalPrice);
        this.save(userOrder);

        //短信通知陪陪
        YunDunClient.sendNotice(skillUser.getPhone(), skillUser.getNickname(),buyer.getNickname());
//        this.sendOrderNotice(buyer.getNickname(), skillUser.getNickname(),skillUser.getPhone());
        return userOrder.getId();
    }

//    public static void main(String[] args) {
//        YunDunClient.sendNotice("19862527916","小龙龙","沐一");
//    }


    private void sendOrderNotice(String buyerNickname, String serviceNickname, String phone) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        Client client = new Client(config);
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("碰心App")
                .setTemplateCode("SMS_269200424")
                .setPhoneNumbers(phone)
                .setTemplateParam(String.format("亲爱的%s，玩家%s 已下单。请您8分钟内及时接单，以免玩家退单。平台严查欺骗用户的行为，涉嫌电竞师封禁。", serviceNickname, buyerNickname));
        // 复制代码运行请自行打印 API 的返回值
        client.sendSms(sendSmsRequest);
    }

    @Override
    public OrderProgressVO getOrderProgress(Long currentUserId, String username) {
        OrderProgressVO vo = new OrderProgressVO();
        User user = userService.getByUsername(username);

        //默认自己不是陪陪
        Boolean isAccompany = false;

        //查询是否自己正在下单中
        LambdaQueryWrapper<UserOrderRecord> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserOrderRecord::getUserId,currentUserId)
                .eq(UserOrderRecord::getTargetUserId,user.getId())
                .eq(UserOrderRecord::getType,1)
                .and(w->w.eq(UserOrderRecord::getStatus, OrderStatusEnums.IN_PROGRESS.getStatus())
                .or().eq(UserOrderRecord::getStatus, OrderStatusEnums.EVALUATE.getStatus())
                .or().eq(UserOrderRecord::getStatus, OrderStatusEnums.PENDING.getStatus())
                        .or().eq(UserOrderRecord::getStatus, OrderStatusEnums.REFUNDING.getStatus()));

        UserOrderRecord userOrder = this.getOne(wrapper);

        //查询对方是否在下单中
        if (userOrder == null){
            wrapper.clear();
            wrapper.eq(UserOrderRecord::getTargetUserId,currentUserId)
                    .eq(UserOrderRecord::getUserId, user.getId())
                    .eq(UserOrderRecord::getType,1)
                    .and(w->w.eq(UserOrderRecord::getStatus, OrderStatusEnums.IN_PROGRESS.getStatus())
                            .or().eq(UserOrderRecord::getStatus, OrderStatusEnums.EVALUATE.getStatus())
                            .or().eq(UserOrderRecord::getStatus, OrderStatusEnums.PENDING.getStatus())
                            .or().eq(UserOrderRecord::getStatus, OrderStatusEnums.REFUNDING.getStatus()));
            userOrder = this.getOne(wrapper);
            if (userOrder == null) {
                return vo;
            }

            //是陪陪
            isAccompany = true;
        }
        vo.setStatus(userOrder.getStatus());
        vo.setIsAccompany(isAccompany);
        vo.setIsPending(true);
        vo.setOrderId(userOrder.getId());
        return vo;
    }

    @Override
    public void receivingOrder(Long userId, Long orderId) {
        UserOrderRecord userOrder = this.getById(orderId);

        Long targetUserId = userOrder.getTargetUserId();
        if (!targetUserId.equals(userId)){
            throw new ServiceException("参数异常！");
        }

        userOrder.setStatus(OrderStatusEnums.IN_PROGRESS.getStatus());
        this.updateById(userOrder);
    }

    @Override
    public void refuseOrder(Long userId, Long orderId) {
        UserOrderRecord userOrder = this.getById(orderId);

        Long targetUserId = userOrder.getTargetUserId();
        if (!targetUserId.equals(userId)){
            throw new ServiceException("参数异常！");
        }

        //退还下单人金币余额
        userService.addBalance(userOrder.getUserId(),BigDecimal.valueOf(userOrder.getTotalPrice()));
        userOrder.setStatus(OrderStatusEnums.REFUSE.getStatus());
        this.updateById(userOrder);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void completeOrder(Long userId, Long orderId) {
        User user = userService.getById(userId);
        UserOrderRecord userOrder = this.getById(orderId);

        if (!userOrder.getStatus().equals(1)){
            throw new ServiceException("订单未在进行中！");
        }

        Long targetUserId = userOrder.getTargetUserId();
        User targetUser = userService.getById(targetUserId);

        Integer totalPrice = userOrder.getTotalPrice();
        String partyId = userOrder.getPartyId();

        Integer skillId = userOrder.getSkillId();
        UserSkill userSkill = userSkillService.getUserSkill(targetUserId, skillId);

        double profit = (totalPrice/100d) * 0.7;
        if (StringUtils.isNotBlank(partyId)){
            //陪陪增加收益
//            profit = (totalPrice/100d) * 0.7;

            //会长收益
            double presidentProfit = (totalPrice/100d) * 0.2;
            //公会流水返利。
            Party party = partyService.getById(partyId);
            Long associationId = party.getAssociationId();
            if (associationId!=null){
                Association association = associationService.getById(associationId);
                Long presidentUserId = association.getPresidentUserId();
                userService.increaseProfit(presidentUserId, BigDecimal.valueOf(presidentProfit));
                this.saveProfitBill(presidentUserId,targetUserId,presidentProfit,user.getNickname(),userSkill.getSkillName());
            }

        }

        userService.increaseProfit(targetUserId, BigDecimal.valueOf(profit));

        if (!userOrder.getStatus().equals(OrderStatusEnums.IN_PROGRESS.getStatus())){
            throw new ServiceException("订单状态有误！");
        }
        Integer userCount = userSkill.getUserCount();
        userCount ++;
        userSkill.setUserCount(userCount);
        userSkillService.updateById(userSkill);

        userOrder.setStatus(OrderStatusEnums.EVALUATE.getStatus());
        this.updateById(userOrder);

        //保存陪陪收益记录
        this.saveProfitBill(targetUserId,user.getId(),profit,user.getNickname(),userSkill.getSkillName());
        //保存板板支出记录
        this.savePayBill(user.getId(),targetUserId, totalPrice.doubleValue(),targetUser.getNickname(),userSkill.getSkillName());
    }

    private void saveProfitBill(Long userId, Long targetUserId,Double profit, String nickname, String skillName){
        UserBill userBill = new UserBill();
        userBill.setUserId(userId);
        userBill.setStatus(Status.SUCCESS.getValue());
        userBill.setTargetId(targetUserId);
        userBill.setNumber(BigDecimal.valueOf(profit).setScale(2, RoundingMode.HALF_UP));
        userBill.setType(UserBillTypeEnum.ORDER.getType());
        userBill.setPm(1);
        userBill.setDescription("用户【"+nickname+"】完成【"+skillName+"】订单，获得收益: "+profit);
        userBill.setCategory(UserBillCategoryEnum.PROFIT.getCategory());
        userBillService.save(userBill);
    }


    private void savePayBill(Long userId, Long targetUserId,Double profit, String nickname, String skillName){
        UserBill userBill = new UserBill();
        userBill.setUserId(userId);
        userBill.setStatus(Status.SUCCESS.getValue());
        userBill.setTargetId(targetUserId);
        userBill.setNumber(BigDecimal.valueOf(profit).setScale(2, RoundingMode.HALF_UP));
        userBill.setType(UserBillTypeEnum.ORDER.getType());
        userBill.setPm(0);
        userBill.setDescription("购买陪陪【"+nickname+"】技能【"+skillName+"】，支出: "+profit);
        userBill.setCategory(UserBillCategoryEnum.BALANCE.getCategory());
        userBillService.save(userBill);
    }

    @Override
    public OrderDetailVO getOrderDetail(Long orderId) {

        UserOrderRecord order = this.getById(orderId);

        Integer skillId = order.getSkillId();
        Long targetUserId = order.getTargetUserId();
        //获取陪陪的技能
        UserSkill userSkill = userSkillService.getUserSkill(targetUserId, skillId);
        if (null == userSkill){
            throw new ServiceException("用户技能不存在！");
        }

        User targetUser = userService.getById(targetUserId);
        OrderDetailVO vo = new OrderDetailVO();
        vo.setUserSkill(userSkill);
        vo.setAvatar(targetUser.getAvatar());
        vo.setNickname(targetUser.getNickname());
        vo.setUserId(targetUserId);
        vo.setOrderId(orderId);
        vo.setUsername(targetUser.getUsername());
        vo.setStatus(order.getStatus());
        vo.setTotalCount(order.getTotalCount());
        vo.setTotalPrice(order.getTotalPrice());
        OrderEvaluateVO evaluateVO = orderEvaluateService.getEvaluate(order.getUserId(),orderId);
        vo.setEvaluate(evaluateVO);
        return vo;
    }



    @Override
    public List<OrderDetailVO> getOrderList(Long userId, Integer type, Integer page, Integer size) {

        if (type == 1){
            //我的下单
            //查看到的是陪陪的头像
            return this.getUserOrderList(userId, page, size);

        }else {
            //获取接单列表
            return this.getReceiveOrderList(userId,page,size);
        }
    }

    @Override
    public List<OrderEvaluateVO> getEvaluateList(Long targetUserId, Integer skillId,Integer page, Integer size) {
        LambdaQueryWrapper<OrderEvaluate> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(OrderEvaluate::getTargetUserId, targetUserId);
        if (null != skillId){
            wrapper.eq(OrderEvaluate::getSkillId, skillId);
        }
        wrapper.orderByDesc(OrderEvaluate::getCreateTime);
        List<OrderEvaluate> records = orderEvaluateService.page(new Page<>(page, size), wrapper).getRecords();
        List<Long> userIds = records.stream().map(OrderEvaluate::getUserId).collect(Collectors.toList());
        List<User> users = Lists.newLinkedList();
        if (!userIds.isEmpty()){
            users = userService.listByIds(userIds);
        }
        List<OrderEvaluateVO> finalList = Lists.newLinkedList();
        for (OrderEvaluate record : records) {
            OrderEvaluateVO vo = new OrderEvaluateVO();
            String tagIds = record.getTagIds();
            if (StringUtils.isNotBlank(tagIds)){
                List<String> tagIdList = Arrays.asList(tagIds.split(","));
                List<String> tagNames = userTagService.listByIds(tagIdList).stream().map(UserTag::getName).collect(Collectors.toList());
                vo.setTags(tagNames);
            }

            vo.setContent(record.getContent());
            vo.setTime(record.getCreateTime());
            vo.setIsSatisfied(record.getIsSatisfied());
            Optional<User> first = users.stream().filter(u -> u.getId().equals(record.getUserId())).findFirst();
            if (first.isPresent()){
                User user = first.get();
                vo.setUserId(user.getId());
                String nickname = user.getNickname();
                vo.setAvatar(user.getAvatar());
                String finalNickname = "";
                if (StringUtils.isNotBlank(nickname)){
                    char lastStr = nickname.charAt(nickname.length() - 1);
                    finalNickname = "****"+lastStr;
                }
                if (record.getIsAnonymous()!=null&&record.getIsAnonymous()){
                    finalNickname = "匿名用户";
                    vo.setAvatar("https://pengxinapp.oss-cn-beijing.aliyuncs.com/avatar/Group%203346108%403x.png");
                }
                vo.setNickname(finalNickname);
                vo.setUsername(user.getUsername());
            }
            finalList.add(vo);
        }
        return finalList;
    }

    /**
     * 判断用户今天有没有买过每日一币
     * @param buyerId
     * @return
     */
    @Override
    public Boolean checkFirstPayOneCoinToday(Long buyerId) {
        Long count = baseMapper.getCount(buyerId);
        if (count>0){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 申请退款
     * @param userId
     * @param dto
     */
    @Override
    public void requestRefund(Long userId, RequestRefundDTO dto) {
        UserOrderRecord order = this.getById(dto.getOrderId());
        if (OrderStatusEnums.IN_PROGRESS.getStatus().equals(order.getStatus())){
            order.setStatus(OrderStatusEnums.REFUNDING.getStatus());
        }else {
            throw new ServiceException("该订单未在进行中！");
        }
        String remark = dto.getRemark();
        Integer type = dto.getType();
        log.info("陪玩订单申请退款，订单id:{}，类型：{}，理由：{}",order.getId(),type,remark);
        if (!order.getUserId().equals(userId)){
            throw new ServiceException("参数异常！");
        }
        this.updateById(order);
    }

    /**
     * 同意退款
     * @param userId
     * @param orderId
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void confirmRefund(Long userId, Long orderId) {
        UserOrderRecord order = this.getById(orderId);

        if (!userId.equals(order.getTargetUserId())){
            throw new ServiceException("参数异常！");
        }

        if (!OrderStatusEnums.REFUNDING.getStatus().equals(order.getStatus())){
            throw new ServiceException("订单未在退款中！");
        }

        //变更订单状态
        order.setStatus(OrderStatusEnums.REFUNDED.getStatus());
        this.updateById(order);
        Integer totalPrice = order.getTotalPrice();
        //退还下单用户的金额
        userService.addBalance(order.getUserId(), BigDecimal.valueOf(totalPrice));
    }

    @Override
    public void refuseRefund(Long userId, Long orderId) {
        UserOrderRecord order = this.getById(orderId);

        if (!userId.equals(order.getTargetUserId())){
            throw new ServiceException("参数异常！");
        }

        if (!OrderStatusEnums.REFUNDING.getStatus().equals(order.getStatus())){
            throw new ServiceException("订单未在退款中！");
        }

        //变更订单状态
        order.setStatus(OrderStatusEnums.IN_PROGRESS.getStatus());
        this.updateById(order);
    }

    @Override
    public void cancelOrder(Long userId, Long orderId) {
        UserOrderRecord order = this.getById(orderId);
        if (!userId.equals(order.getUserId())){
            throw new ServiceException("非下单人无法取消订单！");
        }
        //退回金币
        userService.addBalance(order.getUserId(),BigDecimal.valueOf(order.getTotalPrice()));
        order.setStatus(OrderStatusEnums.CANCEL.getStatus());
        this.updateById(order);
    }

    @Override
    public List<UserOrderRecord> getOvertimeOrders() {
        return baseMapper.getOvertimeOrders();
    }

    @Override
    public Boolean checkFirstPay(Long buyerId, Long userId, Integer skillId) {
        LambdaQueryWrapper<UserOrderRecord> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserOrderRecord::getUserId, buyerId)
                .eq(UserOrderRecord::getTargetUserId, userId)
                .eq(UserOrderRecord::getSkillId, skillId);
        List<UserOrderRecord> list = this.list(wrapper);
        if (CollectionUtil.isEmpty(list)){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }


    /**
     * 获取我的订单列表
     * @param userId
     * @param page
     * @param size
     * @return
     */
    private List<OrderDetailVO> getUserOrderList(Long userId, Integer page, Integer size) {
        LambdaQueryWrapper<UserOrderRecord> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserOrderRecord::getUserId, userId)
                .eq(UserOrderRecord::getType,1)
                .orderByDesc(UserOrderRecord::getCreateTime);

        List<UserOrderRecord> list = this.page(new Page<>(page,size),wrapper).getRecords();

        List<OrderDetailVO> finalList = Lists.newLinkedList();
        for (UserOrderRecord order : list) {
            Integer skillId = order.getSkillId();
            Long targetUserId = order.getTargetUserId();
            //获取陪陪的技能
            UserSkill userSkill = userSkillService.getUserSkill(targetUserId, skillId);
            if (null == userSkill){
                continue;
            }

            User targetUser = userService.getById(targetUserId);
            OrderDetailVO vo = new OrderDetailVO();
            vo.setUserSkill(userSkill);
            vo.setAvatar(targetUser.getAvatar());
            vo.setNickname(targetUser.getNickname());
            vo.setUserId(targetUserId);
            vo.setStatus(order.getStatus());
            vo.setUsername(targetUser.getUsername());
            vo.setOrderId(order.getId());
            vo.setTotalCount(order.getTotalCount());
            vo.setTotalPrice(order.getTotalPrice());
            finalList.add(vo);
        }
        return finalList;
    }

    /**
     * 获取接单列表
     * @param userId
     * @return
     */
    private List<OrderDetailVO> getReceiveOrderList(Long userId, Integer page, Integer size) {
        LambdaQueryWrapper<UserOrderRecord> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(UserOrderRecord::getTargetUserId, userId)
                .eq(UserOrderRecord::getType,1)
                .orderByDesc(UserOrderRecord::getCreateTime);

        User user = userService.getById(userId);

        List<UserSkill> userSkillList = userSkillService.getUserSkillList(userId);
        List<UserOrderRecord> list = this.page(new Page<>(page,size),wrapper).getRecords();

        List<User> buyerUsers = Lists.newLinkedList();

        if (!list.isEmpty()){
            List<Long> buyerUserIds = list.stream().map(UserOrderRecord::getUserId).collect(Collectors.toList());
            buyerUsers = userService.listByIds(buyerUserIds);
        }

        List<OrderDetailVO> finalList = Lists.newLinkedList();
        for (UserOrderRecord order : list) {


            Integer skillId = order.getSkillId();
            //获取陪陪的技能
            OrderDetailVO vo = new OrderDetailVO();
            if (!userSkillList.isEmpty()){
                userSkillList.stream().filter(u -> u.getSkillId().equals(skillId)).findFirst().ifPresent(vo::setUserSkill);
            }

            Optional<User> first = buyerUsers.stream().filter(u -> u.getId().equals(order.getUserId())).findFirst();
            if (first.isPresent()){
                User buyerUser = first.get();
                vo.setAvatar(buyerUser.getAvatar());
                vo.setNickname(buyerUser.getNickname());
                vo.setUserId(buyerUser.getId());
            }

            vo.setStatus(order.getStatus());
            vo.setUsername(user.getUsername());
            vo.setOrderId(order.getId());
            vo.setTotalCount(order.getTotalCount());
            vo.setTotalPrice(order.getTotalPrice());
            finalList.add(vo);
        }

        return finalList;

    }
}
